import './OptionsOpen.scss'

import { Button, Tree, Select } from "antd"
import { useState, useRef, useEffect } from 'react'
import { useMount, useSize } from 'ahooks'
import { Http } from '../../Utils/Api'
import { useRequest } from 'alova/client'
import { devChartsStore } from '../../Config/zustand'

import Chart, { AdaptiveLayout, CommonSeriesSettings, Size, Tooltip, Export, Label, Format, Legend } from 'devextreme-react/chart'

const ChartsType = [
    { value: 'bar', label: '柱图' },
    { value: 'stackedbar', label: '堆叠柱图' },
    { value: 'fullstackedbar', label: '百分比全堆叠' },
    { value: 'splinearea', label: '面积图(重叠)' },
    { value: 'stackedsplinearea', label: '面积图(不重叠)' },
    { value: 'fullstackedsplinearea', label: '百分比面积图' },
    { value: 'spline', label: '折线图' },
    { value: 'stackedspline', label: '堆叠折线图' },
    { value: 'fullstackedspline', label: '百分比折线图' },
]


const OptionsOpen = ({ data, Off }) => {
    const { type, DevEvent, APIdata } = data
    const { send } = useRequest(data => Http(data), { immediate: false })

    if (type === 'A01') {
        const [Loading, setLoading] = useState(false)
        const [TreeData, setTreeData] = useState()
        useMount(() => { send({ method: 'get', url: 'menu' }).then(res => setTreeData(res.data.list)) })

        const onDrop = (info) => {
            const dropKey = info.node.uuid;
            const dragKey = info.dragNode.uuid;
            const dropPos = info.node.pos.split('-');
            const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
            const loop = (data, uuid, callback) => {
                for (let i = 0; i < data.length; i++) {
                    if (data[i].uuid === uuid) return callback(data[i], i, data)
                    if (data[i].children) loop(data[i].children, uuid, callback)
                }
            }
            const data = [...TreeData]
            let dragObj;
            loop(data, dragKey, (item, index, arr) => {
                arr.splice(index, 1)
                dragObj = item
            })
            if (!info.dropToGap) {
                loop(data, dropKey, item => {
                    item.children = item.children || []
                    item.children.unshift(dragObj);
                });
            } else {
                let ar = [], i
                loop(data, dropKey, (_item, index, arr) => { ar = arr; i = index })
                if (dropPosition === -1) ar.splice(i, 0, dragObj)
                else ar.splice(i + 1, 0, dragObj)
            }
            setTreeData(data);
        }

        const onSave = () => {
            setLoading(true)
            send({ method: 'post', url: 'menu/UpdateMenuSortId', params: TreeData }).then(res => {
                DevEvent.emit({ type: 'onRefresh' })
                Off()
            })
        }

        return (
            <div className="OptionsOpenA01">
                {TreeData &&
                    <Tree
                        fieldNames={{ key: 'uuid', title: 'tableName' }}
                        defaultExpandAll
                        draggable
                        blockNode
                        onDrop={onDrop}
                        treeData={TreeData}
                        selectedKeys={[]}
                    />
                }
                <Button type='primary' loading={Loading} style={{ width: 160 }} onClick={onSave}>保存排序</Button>
            </div>
        )
    }
    if (type === 'A04') {
        const chartRef = useRef()
        const chartBox = useRef()
        const size = useSize(chartBox)

        const { devPivot } = devChartsStore()
        const [Type, setType] = useState('bar')

        useEffect(() => {
            if (devPivot.current) {
                console.log(devPivot)
                devPivot.current.instance().bindChart(chartRef.current.instance(), { dataFieldsDisplayMode: 'splitPanes', alternateDataFields: false })
            }
        }, [devPivot])

        const customizeTooltip = (args) => {
            const valueText = args.seriesName.indexOf('Total') !== -1 ?
                new Intl.NumberFormat('en-EN', { style: 'currency', currency: 'USD' }).format(args.originalValue,) : args.originalValue;
            return { html: `${args.seriesName}<div class='currency'>${valueText}</div>` }
        }

        return (
            <div className='OLAPCharts'>
                <div className='Charts' ref={chartBox}>
                    <Chart ref={chartRef}>
                        <Size height={size?.height || 600} />
                        <Tooltip enabled={true} location="edge" customizeTooltip={customizeTooltip} />
                        <Label enabled={true} >
                            <Format precision={1} type="fixedPoint" />
                        </Label>
                        <CommonSeriesSettings type={Type} />
                        <AdaptiveLayout width={600} />
                        <Export enabled={true} />
                        <Legend
                            verticalAlignment="top"
                            horizontalAlignment="center"
                            itemTextPosition="right"
                        />
                    </Chart>
                </div>
                <div className='Options'>
                    <div>图例类型 : </div>
                    <Select value={Type} options={ChartsType} onChange={e => setType(e)} />
                </div>
            </div>
        )
    }

    if (type === 'A05') {
        const [Loading, setLoading] = useState(false)
        const [TreeData, setTreeData] = useState()
        useMount(() => { send({ method: 'get', url: 'weChatMenu' }).then(res => setTreeData(res.data.list)) })

        const onDrop = (info) => {
            const dropKey = info.node.uuid;
            const dragKey = info.dragNode.uuid;
            const dropPos = info.node.pos.split('-');
            const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
            const loop = (data, uuid, callback) => {
                for (let i = 0; i < data.length; i++) {
                    if (data[i].uuid === uuid) return callback(data[i], i, data)
                    if (data[i].children) loop(data[i].children, uuid, callback)
                }
            }
            const data = [...TreeData]
            let dragObj;
            loop(data, dragKey, (item, index, arr) => {
                arr.splice(index, 1)
                dragObj = item
            })
            if (!info.dropToGap) {
                loop(data, dropKey, item => {
                    item.children = item.children || []
                    item.children.unshift(dragObj);
                });
            } else {
                let ar = [], i
                loop(data, dropKey, (_item, index, arr) => { ar = arr; i = index })
                if (dropPosition === -1) ar.splice(i, 0, dragObj)
                else ar.splice(i + 1, 0, dragObj)
            }
            setTreeData(data);
        }

        const onSave = () => {
            setLoading(true)
            send({ method: 'post', url: 'weChatMenu/UpdateMenuSortId', params: TreeData }).then(res => {
                DevEvent.emit({ type: 'onRefresh' })
                Off()
            })
        }

        return (
            <div className="OptionsOpenA01">
                {TreeData &&
                    <Tree
                        fieldNames={{ key: 'uuid', title: 'tableName' }}
                        defaultExpandAll
                        draggable
                        blockNode
                        onDrop={onDrop}
                        treeData={TreeData}
                        selectedKeys={[]}
                    />
                }
                <Button type='primary' loading={Loading} style={{ width: 160 }} onClick={onSave}>保存排序</Button>
            </div>
        )
    }

}

export default OptionsOpen;